﻿using Avalonia.Controls;
using Avalonia.Xaml.Interactivity;

namespace KinonekoSoftware.Studio.Resources.Behaviors
{
    public sealed class OpenContextMenuBehavior : Behavior<Control>
    {
        protected override void OnAttached()
        {
            if (AssociatedObject is null)
            {
                return;
            }
            
            if (AssociatedObject is Avalonia.Controls.Button button)
            {
                button.Click += OnButtonClick;
            }
            else
            {
                AssociatedObject.PointerPressed += OnMouseClick;
            }
            base.OnAttached();
        }

        private static void OnMouseClick(object sender, PointerPressedEventArgs e)
        {
            if (sender is Control control && control.ContextMenu is not null)
            {
                control.ContextMenu.PlacementTarget = control;
                control.ContextMenu.Placement       = PlacementMode.Bottom;
                control.ContextMenu.Open();
            }
        }

        private static void OnButtonClick(object sender, RoutedEventArgs e)
        {
            if (sender is Control control && control.ContextMenu is not null)
            {
                control.ContextMenu.PlacementTarget = control;
                control.ContextMenu.Placement       = PlacementMode.Bottom;
                control.ContextMenu.Open();
            }
        }

        protected override void OnDetaching()
        {
            if (AssociatedObject is null)
            {
                return;
            }
            
            if (AssociatedObject is Avalonia.Controls.Button button)
            {
                button.Click -= OnButtonClick;
            }
            else
            {
                AssociatedObject.PointerPressed -= OnMouseClick;
            }
            base.OnDetaching();
        }
    }
}